<template>
  <div class="edit">
    <div class="edit-title">
      <span class="title-1">试卷管理</span> / <span class="title-2">{{ pageTitle }}</span>
    </div>
    <div class="edit-content">
      <div class="edit-content-title">{{ contentTitle }}</div>
      <div class="edit-content-form">
        <el-form :label-position="labelPosition" label-width="80px" :model="formLabelAlign" style="margin-bottom: 40px">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="试卷名称">
                  <el-input v-model="formLabelAlign.fullName" :disabled="disableAll" class="set-form-wid" placeholder="请输入试卷名称"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="出题方式">
                  <el-select v-model="formLabelAlign.paperType" :disabled="disableAll" placeholder="请选择试卷类型" class="set-form-wid">
                    <el-option label="手动出题" value="1"></el-option>
                    <el-option label="自动出题" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="总分">
                  <el-input v-model="formLabelAlign.myScore" disabled class="set-form-wid" placeholder="请输入总分"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="grid-content bg-purple">
                <el-form-item label="试卷编号">
                  <el-input v-model="formLabelAlign.enCode" :disabled="disableAll" class="set-form-wid" placeholder="请输入试卷编号"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="16">
              <div class="grid-content bg-purple">
                <el-form-item label="试卷描述">
                  <el-input type="textarea" v-model="formLabelAlign.description" maxlength="500" show-word-limit :disabled="disableAll" style="width: 79.5%" placeholder="请输入试卷描述"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="grid-content bg-purple">
                <el-form-item label="试卷说明">
                  <el-input type="textarea" v-model="formLabelAlign.intro" maxlength="500" show-word-limit :disabled="disableAll" class="" style="width: 86.3%" placeholder="请输入试卷说明"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
        <div class="set-btn-add">
          <el-button v-if="activeName != 'three'" @click="addExamList" :disabled="disableAll">添加题目</el-button>
        </div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="手动选题" name="first">
            <el-table ref="multipleTable1" :data="tableData3" tooltip-effect="dark" style="width: 100%" max-height="250"
              @selection-change="handleManualSelectionChange">
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="题目标签">
                <template slot-scope="scope">
                  {{ scope.row.labels | dynamicText(labelListOptions) }}
                </template>
              </el-table-column>
              <el-table-column prop="questionType" label="题目类型">
                <template slot-scope="scope">
                  <div class="gizall">
                    <div class="tag" v-if="scope.row.questionType">{{
                      getQuestionTypeName(Number(scope.row.questionType)) }}</div>
                    <span v-else>--</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="title" label="题目名称">
                <template slot-scope="scope">
                  <div class="gizall">
                    <div class="gjz" v-if="scope.row.title">{{ scope.row.title }}</div>
                    <span v-else>--</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="120" align="center">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="editRow(scope.row)" :disabled="disableAll" type="text" size="small" class="delete-btn">
                    <i class="el-icon-delete"></i>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="自动选题" name="second">
            <el-table ref="multipleTable1" :data="tableData4" tooltip-effect="dark" style="width: 100%" max-height="250"
              @selection-change="handleAutoSelectionChange">
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="题目标签">
                <template slot-scope="scope">
                  {{ scope.row.labels | dynamicText(labelListOptions) }}
                </template>
              </el-table-column>
              <el-table-column prop="questionType" label="题目类型">
                <template slot-scope="scope">
                  <div class="gizall">
                    <div class="tag" v-if="scope.row.questionType">{{
                      getQuestionTypeName(Number(scope.row.questionType)) }}</div>
                    <span v-else>--</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="title" label="题目名称">
                <template slot-scope="scope">
                  <div class="gizall">
                    <div class="gjz" v-if="scope.row.title">{{ scope.row.title }}</div>
                    <span v-else>--</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="120" align="center">
                <template slot-scope="scope">
                  <el-button @click.native.prevent="editRow(scope.row)" :disabled="disableAll" type="text" size="small" class="delete-btn">
                    <i class="el-icon-delete"></i>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="分值设置" name="three">
            <div class="sjform-tip">
              <i class="el-icon-warning-outline"></i>分值设置：系统判断总分必须等于100分
            </div>
            <el-table :data="scoreData" style="width: 100%">
              <el-table-column prop="multipleScore" label="多选题分值">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.multipleScore" :min="0" :max="100" placeholder="请输入分值" @change="compareTotalScore"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column prop="judgeScore" label="判断题分值">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.judgeScore" :min="0" :max="100" placeholder="请输入分值" @change="compareTotalScore"></el-input-number>
                </template>
              </el-table-column>
            </el-table>
            <!--总分-->
            <div style="margin-top: 40px; font-size: 16px;">总分：{{ formLabelAlign.totalScore }}</div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="edit-footer">
      <el-button class="edit-footer-btn" @click="goback">返回</el-button>
      <el-button type="primary" :loading="isAdding" :disabled="isAdding" @click="submitItem" v-if="!disableAll">保存</el-button>
    </div>
    <!-- 弹窗 -->
    <el-drawer :visible.sync="openAddTitle" :with-header="false" :direction="direction" size="60%">
      <div class="drawer-title">
        <div class="drawer-title-left">{{ addTitle }}</div>
        <div class="drawer-title-right" @click="openAddTitle = false">
          <i class="el-icon-close" style="font-size: 14px; color: #a4afca"></i>
        </div>
      </div>
      <div class="drawer-content" style="display: flex; flex-direction: column; gap: 24px">
        <div class="search-form">
          <el-form :inline="true" :model="drawerSearchForm" class="demo-form-inline">
            <!-- 只在手动出题模式下显示题型选择 -->
            <el-form-item label="题型" v-if="formLabelAlign.paperType === '1'">
              <el-select v-model="drawerSearchForm.questionType" placeholder="请选择题型" clearable>
                <el-option label="判断题" value="determine"></el-option>
                <el-option label="选择题" value="multiple"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题目标签">
              <el-select
                v-model="drawerSearchForm.labels"
                placeholder="请选择题目标签"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in labelsOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.enCode"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="难度">
              <el-select v-model="drawerSearchForm.difficultyGradeId" placeholder="请选择难度" clearable>
                <el-option label="简单" value="1"></el-option>
                <el-option label="中等" value="2"></el-option>
                <el-option label="困难" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题干">
              <el-input v-model="drawerSearchForm.title" placeholder="请输入题干关键字"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
          <!-- 自动出题模式下显示题目数量选择 -->
          <div v-if="formLabelAlign.paperType === '2'" class="question-count-form">
            <el-form :inline="true" :model="autoQuestionCounts">
              <el-form-item label="判断题数量">
                <el-input-number 
                  v-model="autoQuestionCounts.determine" 
                  :min="0" 
                  :max="questionTypeLimits.determine"
                  size="small">
                </el-input-number>
                <span class="question-count-limit">/{{ questionTypeLimits.determine }}</span>
              </el-form-item>
              <el-form-item label="选择题数量">
                <el-input-number 
                  v-model="autoQuestionCounts.multiple" 
                  :min="0" 
                  :max="questionTypeLimits.multiple"
                  size="small">
                </el-input-number>
                <span class="question-count-limit">/{{ questionTypeLimits.multiple }}</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <el-table ref="multipleTable1" :data="tableData2" tooltip-effect="dark" style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="题目标签" width="150">
            <template slot-scope="scope">
              {{ scope.row.labels | dynamicText(labelListOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="questionType" label="题目类型" width="150">
            <template slot-scope="scope">
              <div class="gizall">
                <div class="tag" v-if="scope.row.questionType">{{ getQuestionTypeName(scope.row.questionType) }}</div>
                <span v-else>--</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="题目名称">
            <template slot-scope="scope">
              <div class="gizall">
                <div class="gjz" v-if="scope.row.title">{{ scope.row.title }}</div>
                <span v-else>--</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="set-r">
          <div>
            <div class="pagination-container">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage2" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize2"
                layout="sizes, prev, pager, next, total" :total="total2">
              </el-pagination>
            </div>
          </div>
          <div><el-button @click="addExam()">确定</el-button></div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { addCourse } from "@/api/dataCenter/dataCenterApi";
import { getQuestionList } from "@/api/test/question";
import { addList, getDetail,Update } from "./api/exam";
export default {
  data() {
    return {
      isAdding: false,
      direction: "rtl",
      openAddTitle: false,
      addTitle: '手动选题',
      activeName: "first",
      labelPosition: "top",
      disableAll: false,
      formLabelAlign: {
        fullName: "",
        paperType: "1",
        passScore: 60,
        passLine: 60,
        myScore: 100,
        description: "",
        intro: "",
        categoryId: "638393419709834757",
        enCode: "",
        folders: "",
        enabledMark: null,
        rules: [],
        id: "",
        deleteMark: null,
        totalScore: '',
        questions: []
      },
      tableData2: [{}],
      tableDataList: [{}],
      isOk: true,
      currentPage2: 1,
      pageSize2: 10,
      total2: 0,
      input: '',
      tableData3: [],
      currentPage3: 1,
      pageSize3: 10,
      total3: 0,
      tableData4: [],
      currentPage4: 1,
      pageSize4: 10,
      total4: 0,
      selectedQuestions: [],
      selectedManual: [],
      selectedAuto: [],
      pageTitle: '新增',
      contentTitle: '新增试卷',
      searchForm: {
        questionType: '',
        labels: '',
        difficultyGradeId: '',
        title: ''
      },
      scoreData: [{
        singleScore: 0,
        multipleScore: 0,
        judgeScore: 0,
        fillScore: 0,
        questionScore: 0,
        passScore: 60,
        multipleQuestionNum: 0,  // 选择题
        judgeQuestionNum: 0,     // 判断题
        fillQuestionNum: 0,      // 填空题
        questionNum: 0,          // 问答题
      }],
      drawerSearchForm: {
        questionType: '',
        labels: '',
        difficultyGradeId: '',
        title: ''
      },
      autoQuestionCounts: {
        determine: 0,  // 判断题数量
        blank: 0,      // 填空题数量
        multiple: 0,   // 选择题数量
        answers: 0     // 问答题数量
      },
      questionTypeLimits: {
        determine: 0,
        blank: 0,
        multiple: 0,
        answers: 0
      },
      labelsOptions: [],
      labelListOptions:[],
    };
  },
  watch: {
    'formLabelAlign.paperType': {
      handler(newVal) {
        if (newVal === '1') {
          this.activeName = 'first';
          this.addTitle = '手动选题';
          // this.tableData4 = [];
          // this.selectedAuto = [];
        } else if (newVal === '2') {
          this.activeName = 'second';
          this.addTitle = '自动选题';
          // this.tableData3 = [];
          // this.selectedManual = [];
        } else if (newVal === '3') {
          this.activeName = 'three';
          this.addTitle = '分值设置';
        }
      },
      immediate: true
    },
    // activeName: {
    //   handler(newVal) {
    //     const paperType = newVal === 'first' ? '1' : '2';
    //     if (this.formLabelAlign.paperType !== paperType) {
    //       this.formLabelAlign.paperType = paperType;
    //       this.addTitle = newVal === 'first' ? '手动选题' : '自动选题';
    //     }
    //   },
    //   immediate: true
    // }
  },
  created() {
    this.getexamList();
    this.initPageTitle();
    this.initData();
  },
  mounted() {
  },
  methods: {
    initPageTitle() {
      const type = this.$route.query.type;
      switch(type) {
        case 'edit':
          this.pageTitle = '编辑';
          this.contentTitle = '编辑试卷';
          break;
        case 'detail':
          this.pageTitle = '详情';
          this.contentTitle = '试卷详情';
          break;
        default:
          this.pageTitle = '新增';
          this.contentTitle = '新增试卷';
      }
    },
    changeItem() {
      this.isOk = !this.isOk;
    },
    goback() {
      this.$router.go(-1);
    },
    async submitItem() {

      // 防止重复点击
      if (this.isAdding) return;
      this.isAdding = true;

      // 构建参数对象
      const params = {
        folders: "[\"638100473177446981\"]",
        paperrandomVersion: '1',
        categoryId: "638393419709834757",
        enCode: this.formLabelAlign.enCode,
        fullName: this.formLabelAlign.fullName,
        intro: this.formLabelAlign.intro,
        passLine: this.formLabelAlign.passLine,
        myScore: this.formLabelAlign.myScore,
        passScore: this.formLabelAlign.passScore,
        description: this.formLabelAlign.description,
        enabledMark: null,
        rules: [],
        questions: [],
        id: "",
        deleteMark: null,
        paperType: this.formLabelAlign.paperType
      }

      // 添加试题数据
      if (this.formLabelAlign.paperType == 1) {
        params.questions = this.tableData3.map(item => {
          // 根据 questionType 确定对应的 score 字段
          let score;
          switch(Number(item.questionType)) {
            case 1: // 判断题
              score = this.scoreData[0].judgeScore;
              break;
            case 2: // 填空题
              score = this.scoreData[0].fillScore;
              break;
            case 3: // 选择题
              score = this.scoreData[0].multipleScore;
              break;
            case 4: // 问答题
              score = this.scoreData[0].questionScore;
              break;
            default:
              score = 1; // 默认值
          }

          return {
            questionId: item.id,
            questionName: item.title || "",
            questionType: this.getQuestionType(item.questionType),
            questionTypeName: this.getQuestionTypeName(Number(item.questionType)),
            score: score, // 使用动态计算的 score
            missedScore: 0,
            scoreType: "2",
            subQuestionScoreRule: "1"
          };
        });
      } else if (this.formLabelAlign.paperType == 2) {
        params.questions = this.tableData4.map(item => ({
          questionId: item.id,
          questionName: item.title || "",
          questionType: this.getQuestionType(item.questionType),
          questionTypeName: this.getQuestionTypeName(Number(item.questionType)),
          score: 1,
          missedScore: 0,
          scoreType: "2",
          subQuestionScoreRule: "1"
        }));
      }

      // 提示
      if (params.questions.length == 0 ) {
        this.$message.error('请选择题目！');
        return;
      }

      // 请设置分值
      let scoreAll = Number(this.scoreData[0].multipleScore) + Number(this.scoreData[0].judgeScore) + Number(this.scoreData[0].fillScore) + Number(this.scoreData[0].questionScore);
      if (scoreAll == 0) {
        this.$message.error('请设置分值！');
        return;
      }

      let flags = this.compareTotalScore();
      if(!flags) {
        this.$message.error('总分必须等于100分！');
        return;
      } 

      // 分值设置
      params.rules = [
        {
            "questionType": "multiple", // 选择题
            "difficultyGradeId": 0,
            "questionNum": this.scoreData[0].multipleQuestionNum,
            "score": this.scoreData[0].multipleScore,
            "missedScore": 0
        },
        {
            "questionType": "determine",  // 判断题
            "difficultyGradeId": 0,
            "questionNum": this.scoreData[0].judgeQuestionNum,
            "score": this.scoreData[0].judgeScore,
            "missedScore": 0
        },
        {
            "questionType": "blank",  //填空题
            "difficultyGradeId": 0,
            "questionNum": this.scoreData[0].fillQuestionNum,
            "score": this.scoreData[0].fillScore,
            "missedScore": 0
        },
        {
            "questionType": "answers", //问答题
            "difficultyGradeId": 0,
            "questionNum": this.scoreData[0].questionNum,
            "score": this.scoreData[0].questionScore,
            "missedScore": 0
        }
      ];

      try {
        const type = this.$route.query.type;
        let res;
        if (type === 'edit') {
          // 编辑模式，调用更新接口
          params.id = this.$route.query.id; // 添加ID参数
          res = await Update(params);
          if (res.code === 200) {
            this.$message.success('更新成功');
            this.$router.go(-1);
          } else {
            this.$message.error(res.msg || '更新失败');
          }
        } else {
          // 新增模式，调用新增接口
          res = await addList(params);
          if (res.code === 200) {
            this.$message.success('添加成功');
            this.$router.go(-1);
          } else {
            this.$message.error(res.msg || '添加失败');
          }
        }
      } catch (error) {
        this.isAdding = false;
        console.error('操作失败:', error);
        this.$message.error('操作失败');
      }
    },
    // 添加新的辅助方法用于转换题目类型
    getQuestionType(type) {
      switch (Number(type)) {
        case 1:
          return 'determine'; // 判断题
        case 2:
          return 'blank'; // 填空题
        case 3:
          return 'multiple'; // 选择题
        case 4:
          return 'answers'; // 问答题
        default:
          return '';
      }
    },
    addExamList() {
      if (this.activeName === 'first') {
        this.addTitle = '手动选题';
        this.openAddTitle = true;
        this.formLabelAlign.paperType = '1';
        this.drawerSearchForm = {
          questionType: '',
          labels: '',
          difficultyGradeId: '',
          title: ''
        };
      } else {
        this.addTitle = '自动选题';
        this.openAddTitle = true;
        this.formLabelAlign.paperType = '2';
        this.drawerSearchForm = {
          questionType: '',
          labels: '',
          difficultyGradeId: '',
          title: ''
        };
      }
      // 打开抽屉后再获取题目列表
      this.$nextTick(() => {
        this.currentPage2 = 1; // 重置页码
        this.getexamList();
      });
      
      this.getLabelsOptions();
    },
    // 获取 标签 选项
    getLabelsOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "questionLabels",
        })
        .then((res) => {
          this.labelsOptions = res;
          // 转换
          let arr = [];
          for(let i in res) {
            let obj = {};
            obj.fullName = res[i].fullName;
            obj.id = res[i].enCode;
            arr.push(obj);
          }
          this.labelListOptions = arr;
        });
    },
    async getexamList() {
      try {
        let params = {
          currentPage: this.currentPage2,
          pageSize: this.pageSize2,
          labels: this.drawerSearchForm.labels,
          difficultyGradeId: this.drawerSearchForm.difficultyGradeId,
          title: this.drawerSearchForm.title,
          enabledMark: 1
        };
        
        // 只在手动出题模式下添加 questionType 参数
        if (this.formLabelAlign.paperType === '1') {
          params.questionType = this.drawerSearchForm.questionType;
        }
        
        // 移除空值参数
        Object.keys(params).forEach(key => {
          if (!params[key]) {
            delete params[key];
          }
        });

        const response = await getQuestionList(params);
        if (response && response.data) {
          this.tableData2 = response.data.list.map(item => ({
            id: item.id || '',
            questionType: this.getQuestionTypeNumber(item.questionType),
            title: item.title || '--',
            labels: item.labels || ''
          }));
          this.total2 = parseInt(response.data.pagination.total);
          this.currentPage2 = parseInt(response.data.pagination.currentPage);
          this.pageSize2 = parseInt(response.data.pagination.pageSize);
          
          // 更新题型数量限制
          this.updateQuestionTypeLimits();
        }
      } catch (error) {
        console.error("Error fetching list:", error);
        this.$message.error("获取列表失败");
      }
    },
    searchQuestion() {
      let params = {
        title: this.input
      };
      const response = getQuestionList(params);
      if (response && response.data) {
        this.tableData2 = response.data.list.map(item => ({
          ...item,
        }));
        this.total2 = parseInt(response.data.pagination.total);
        this.currentPage2 = parseInt(response.data.pagination.currentPage);
        this.pageSize2 = parseInt(response.data.pagination.pageSize);
      }
    },
    handleSelectionChange(val) {
      this.selectedQuestions = val;
    },
    handleManualSelectionChange(val) {
      this.selectedManual = val;
    },
    handleAutoSelectionChange(val) {
      this.selectedAuto = val;
    },
    handleSizeChange(val) {
      this.pageSize2 = val;
      this.getexamList();
    },
    handleCurrentChange(val) {
      this.currentPage2 = val;
      this.getexamList();
    },
    paramsTranslater() {  
      // 分值设置
      if (this.formLabelAlign.paperType == 1) {
        // 手动选题
        this.scoreData[0].multipleQuestionNum = 0;
        this.scoreData[0].judgeQuestionNum = 0;
        this.scoreData[0].fillQuestionNum = 0;
        this.scoreData[0].questionNum = 0;
        this.tableData3.forEach(item => {
          let questionType = this.getQuestionType(item.questionType);
          if (questionType == 'multiple') {  
            this.scoreData[0].multipleQuestionNum++;   // 选择题
          }
          else if (questionType == 'determine') {
            this.scoreData[0].judgeQuestionNum++;      // 判断题
          }
          else if (questionType == 'blank') {
            this.scoreData[0].fillQuestionNum++;      // 填空题
          }
          else if (questionType == 'answers') {
            this.scoreData[0].questionNum++;           // 问答题
          }
        })
      } else if (this.formLabelAlign.paperType == 2) {
        // 自动选题
        this.scoreData[0].multipleQuestionNum = 0;
        this.scoreData[0].judgeQuestionNum = 0;
        this.scoreData[0].fillQuestionNum = 0;
        this.scoreData[0].questionNum = 0;
        this.tableData4.forEach(item => {
          let questionType = this.getQuestionType(item.questionType);
          if (questionType == 'multiple') {
            this.scoreData[0].multipleQuestionNum++;   // 选择题
          }
          else if (questionType == 'determine') {
            this.scoreData[0].judgeQuestionNum++;      // 判断题
          }
          else if (questionType == 'blank') {
            this.scoreData[0].fillQuestionNum++;      // 填空题
          }
          else if (questionType == 'answers') {
            this.scoreData[0].questionNum++;           // 问答题
          }
        })
      }
      this.$forceUpdate();
    },
    // 计算试卷总分
    compareTotalScore() {
      this.paramsTranslater();
      // 分值总和
      let multipleScoreAll = 0, judgeScoreAll = 0, fillScoreAll = 0, questionScoreAll = 0;
      if (this.scoreData[0].multipleQuestionNum && this.scoreData[0].multipleScore) {
        multipleScoreAll = Number(this.scoreData[0].multipleQuestionNum) * Number(this.scoreData[0].multipleScore);
      }
      if (this.scoreData[0].judgeQuestionNum && this.scoreData[0].judgeScore) {
        judgeScoreAll = Number(this.scoreData[0].judgeQuestionNum) * Number(this.scoreData[0].judgeScore);
      }
      if (this.scoreData[0].fillQuestionNum && this.scoreData[0].fillScore) {
        fillScoreAll = Number(this.scoreData[0].fillQuestionNum) * Number(this.scoreData[0].fillScore);
      }
      if (this.scoreData[0].questionNum && this.scoreData[0].questionScore) {
        questionScoreAll = Number(this.scoreData[0].questionNum) * Number(this.scoreData[0].questionScore);
      }
      // 总分赋值
      this.formLabelAlign.totalScore = multipleScoreAll + judgeScoreAll + fillScoreAll + questionScoreAll;
      let flag = true;
      if (this.formLabelAlign.totalScore != 100) {
        // this.$message.error('总分必须等于100分！');
        flag = false;
        return false;
      }
      return flag;

      // // 总分默认为0
      // let totalScore = 0;
      // const questions = (this.formLabelAlign.paperType == "2" || this.tableData4.length > 0) ? this.tableData4 : this.tableData3;
      // if (questions.length > 0) {
      //   questions.forEach(item => {
      //     if (item.questionType == "1") {
      //       // 判断题
      //       totalScore += this.scoreData[0].judgeScore || 0;
      //     } else if (item.questionType == "2") {
      //       // 填空题
      //       totalScore += this.scoreData[0].fillScore || 0;
      //     } else if (item.questionType == "3") {
      //       // 选择题
      //       totalScore += this.scoreData[0].multipleScore || 0;
      //     } else if (item.questionType == "4") {
      //       // 问答题
      //       totalScore += this.scoreData[0].questionScore || 0;
      //     }
      //   })
      // }
      // // 总分赋值
      // this.formLabelAlign.totalScore = totalScore;
    },
    getQuestionTypeNumber(type) {
      switch (type) {
        case 'determine':
          return 1;
        case 'blank':
          return 2;
        case 'multiple':
          return 3;
        case 'answers':
          return 4;
        default:
          return type ? Number(type) : 0;
      }
    },
    getQuestionTypeName(type) {
      const numType = typeof type === 'string' ? this.getQuestionTypeNumber(type) : Number(type);
      switch (numType) {
        case 1:
          return '判断题';
        case 2:
          return '填空题';
        case 3:
          return '选择题';
        case 4:
          return '问答题';
        default:
          return '--';
      }
    },
    addExam() {
      if (this.formLabelAlign.paperType === '2') {
        // 自动出题模式
        const totalCount = Object.values(this.autoQuestionCounts).reduce((a, b) => a + b, 0);
        if (totalCount === 0) {
          this.$message.warning('请选择要添加的题目数量');
          return;
        }

        // 按题型分组现有题目
        const questionsByType = {};
        this.tableData2.forEach(question => {
          const type = this.getQuestionType(question.questionType);
          if (!questionsByType[type]) {
            questionsByType[type] = [];
          }
          questionsByType[type].push(question);
        });

        // 随机选择每种类型的题目
        const selectedQuestions = [];
        for (const [type, count] of Object.entries(this.autoQuestionCounts)) {
          if (count > 0) {
            const availableQuestions = questionsByType[type] || [];
            if (availableQuestions.length < count) {
              this.$message.warning(`${this.getQuestionTypeName(this.getQuestionTypeNumber(type))}数量不足`);
              return;
            }
            
            // 随机选择指定数量的题目
            const shuffled = [...availableQuestions].sort(() => 0.5 - Math.random());
            selectedQuestions.push(...shuffled.slice(0, count));
          }
        }

        // 添加到表格
        const newQuestions = selectedQuestions.filter(newQuestion => {
          return !this.tableData4.some(existingQuestion => existingQuestion.id === newQuestion.id);
        });
        
        this.tableData4 = [...this.tableData4, ...newQuestions];
        this.$message.success('添加题目成功');
        this.openAddTitle = false;
        
        // 重置计数器
        Object.keys(this.autoQuestionCounts).forEach(key => {
          this.autoQuestionCounts[key] = 0;
        });
      } else {
        // 手动出题模式的原有逻辑
        if (!this.selectedQuestions || this.selectedQuestions.length === 0) {
          this.$message.warning('请选择要添加的试题');
          return;
        }

        const mappedQuestions = this.selectedQuestions.map(question => ({
          id: question.id,
          title: question.title,
          questionType: question.questionType,
          labels: this.getQuestionTypeName(question.questionType)
        }));

        const newQuestions = mappedQuestions.filter(newQuestion => {
          return !this.tableData3.some(existingQuestion => existingQuestion.id === newQuestion.id);
        });
        this.tableData3 = [...this.tableData3, ...newQuestions];
        this.$message.success('添加题目成功');
        this.openAddTitle = false;
        this.selectedQuestions = [];
      }
      // 计算总分
      this.compareTotalScore();
    },
    editRow(row) {
      if (this.activeName === 'first') {
        const index = this.tableData3.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.tableData3.splice(index, 1);
        }
      } else {
        const index = this.tableData4.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.tableData4.splice(index, 1);
        }
      }
      this.$message.success('删除成功');
      // 计算总分
      this.compareTotalScore();
    },
    async searchQuestion() {
      try {
        let params = {
          title: this.input,
          currentPage: this.currentPage2,
          pageSize: this.pageSize2,
          enabledMark: 1
        };
        const response = await getQuestionList(params);
        if (response && response.code === 0) {
          this.tableData2 = response.data.list.map(item => ({
            id: item.id || '',
            questionType: item.questionType || '',
            title: item.title || '--',
            creatorTime: item.creatorTime || '--'
          }));

          if (response.data.pagination) {
            this.total2 = parseInt(response.data.pagination.total) || 0;
            this.currentPage2 = parseInt(response.data.pagination.currentPage) || 1;
            this.pageSize2 = parseInt(response.data.pagination.pageSize) || 10;
          }
        }
      } catch (error) {
        console.error("Error searching questions:", error);
        this.$message.error("搜索失败");
      }
    },
    deleteSelected() {
      if (this.activeName === 'first') {
        if (this.selectedManual.length === 0) {
          this.$message.warning('请选择要删除的试题');
          return;
        }
        const selectedIds = this.selectedManual.map(item => item.id);
        this.tableData3 = this.tableData3.filter(item => !selectedIds.includes(item.id));
        this.selectedManual = [];
      } else {
        if (this.selectedAuto.length === 0) {
          this.$message.warning('请选择要删除的试题');
          return;
        }
        const selectedIds = this.selectedAuto.map(item => item.id);
        this.tableData4 = this.tableData4.filter(item => !selectedIds.includes(item.id));
        this.selectedAuto = [];
      }
      this.$message.success('删除成功');
    },
    handleClick(tab) {
      this.activeName = tab.name;
      if (this.activeName == 'first') {
        this.formLabelAlign.paperType = '1';
      } else if (this.activeName == 'second') {
        this.formLabelAlign.paperType = '2';
      }
    },
    async initData() {

      const id = this.$route.query.id;
      const type = this.$route.query.type;
      const state = this.$route.state || {};

      if (id && (type === 'edit' || type === 'detail')) {

        try {
          let res;
          // 如果有路由状态数据，直接使用
          if (state.formData && state.questions) {
            this.formLabelAlign = {
              ...this.formLabelAlign,
              ...state.formData
            };

            // 根据activeName设置对应的表格数据
            const mappedQuestions = state.questions.map(question => ({
              id: question.questionId,
              title: question.questionName,
              questionType: this.getQuestionTypeNumber(question.questionType),
              labels: question.labels
              // labels: this.getQuestionTypeName(this.getQuestionTypeNumber(question.questionType))
            }));

            if (this.activeName === 'first') {
              this.tableData3 = mappedQuestions;
            } else {
              this.tableData4 = mappedQuestions;
            }
          } else {
            // 如果没有路由状态数据，则调用API获取
            res = await getDetail(id);
            if (res.code === 200) {
              // 填充表单数据
              this.formLabelAlign = {
                fullName: res.data.fullName || '',
                paperType: res.data.paperType || '1',
                passScore: res.data.passScore || 60,
                passLine: res.data.passLine || 60,
                myScore: res.data.myScore || 100,
                description: res.data.description || '',
                intro: res.data.intro || '',
                categoryId: res.data.categoryId || '638393419709834757',
                enCode: res.data.enCode || '',
                // paperrandomVersion: res.data.paperrandomVersion || '',
                folders: res.data.folders || '',
                enabledMark: res.data.enabledMark || null,
                rules: res.data.rules || [],
                id: res.data.id || '',
                deleteMark: res.data.deleteMark || null,
                totalScore: 100
              };
              
              // 处理试题数据
              if (res.data.questions && Array.isArray(res.data.questions)) {
                const questions = res.data.questions.map(question => {
                  // 处理规则rules
                  if (this.formLabelAlign.paperType == 1) {
                    if (question.questionType == 'determine') {  
                      // 判断题
                      this.scoreData[0].judgeScore = question.score;
                    }
                    else if (question.questionType == 'blank') {
                      // 填空题
                      this.scoreData[0].fillScore = question.score;
                    }
                    else if (question.questionType == 'multiple') {
                      // 选择题
                      this.scoreData[0].multipleScore = question.score;
                    }
                    else if (question.questionType == 'answers') {
                      // 问答题
                      this.scoreData[0].questionScore = question.score;
                    }
                  }
                  return {
                    id: question.questionId,
                    title: question.questionName,
                    questionType: this.getQuestionTypeNumber(question.questionType),
                    labels: question.labels
                  }
                });

                this.$nextTick(() => {
                  if (this.activeName === 'first') {
                    this.tableData3 = questions;
                  } else {
                    this.tableData4 = questions;
                  }
                })
              }

              // 处理规则rules
              if (this.formLabelAlign.paperType == 2) {
                if (res.data.rules && Array.isArray(res.data.rules)) {
                  res.data.rules.forEach(item => {
                    if (item.questionType == 'multiple') {   // 选择题
                      this.scoreData[0].multipleScore = item.score;
                    }
                    else if (item.questionType == 'determine') {   // 判断题
                      this.scoreData[0].judgeScore = item.score;
                    }
                    else if (item.questionType == 'blank') {   // 填空题
                      this.scoreData[0].fillScore = item.score;
                    }
                    else if (item.questionType == 'answers') {   // 问答题
                      this.scoreData[0].questionScore = item.score;
                    }
                  })
                }
              }

            } else {
              this.$message.error(res.msg || '获取详情失败');
            }
          }

          // 如果是详情模式，禁用所有输入
          if (type === 'detail') {
            this.disableAll = true;
          }

          this.getLabelsOptions();

        } catch (error) {
          console.error('获取详情失败:', error);
          this.$message.error('获取详情失败');
        }
      }
    },
    handleSearch() {
      this.currentPage2 = 1;
      this.getexamList();
    },
    resetSearch() {
      this.drawerSearchForm = {
        questionType: '',
        labels: '',
        difficultyGradeId: '',
        title: ''
      };
      if (this.formLabelAlign.paperType === '2') {
        Object.keys(this.autoQuestionCounts).forEach(key => {
          this.autoQuestionCounts[key] = 0;
        });
      }
      this.handleSearch();
    },
    // 更新题型数量限制
    updateQuestionTypeLimits() {
      const counts = {
        determine: 0,
        blank: 0,
        multiple: 0,
        answers: 0
      };
      
      this.tableData2.forEach(item => {
        const type = this.getQuestionType(item.questionType);
        if (counts[type] !== undefined) {
          counts[type]++;
        }
      });
      
      this.questionTypeLimits = counts;
    },
  },
};
</script>
<style lang="scss" scoped>
.set-r {
  display: flex;
  width: 100%;

  div:nth-child(1) {
    flex: 8;
  }

  div:nth-child(2) {
    flex: 2;

    .el-button {
      width: 106px;
      height: 36px;
      background-color: #2265ee;
      border: 1px solid #2265ee;
      color: #fff;

      &:active {
        opacity: 0.8;
      }
    }
  }
}

.title-top {
  margin-top: 32px;
}

.edit {
  box-sizing: border-box;
  height: 100%;
  position: relative;

  .edit-title {
    font-weight: 500;
    font-size: 19px;
    color: #536387;
    line-height: 29px;
    text-align: left;
    font-style: normal;

    .title-1 {
      color: #536387;
      padding-right: 11px;
    }

    .title-2 {
      padding-left: 11px;
      color: #323232;
    }
  }

  .edit-content {
    width: 100%;
    height: auto;
    background: #fff;
    box-sizing: border-box;
    padding: 32px;
    margin-top: 32px;

    .edit-content-title {
      font-size: 21px;
      width: 100%;
      height: 39px;
      line-height: 21px;
      position: relative;
      padding-left: 11px;
      border-bottom: 1px solid #e2e7f5;

      &:before {
        content: "";
        position: absolute;
        width: 4px;
        height: 21px;
        top: 0;
        left: 0;
        background: #2265ee;
        display: inline-block;
      }
    }

    .edit-content-form {
      margin-top: 32px;
      margin-bottom: 100px;
      margin-left: 24px;
    }
  }

  .edit-footer {
    width: 100%;
    height: 103px;
    position: fixed;
    bottom: 0;
    left: 0;
    background: #fff;
    text-align: right;
    line-height: 103px;
    z-index: 1000;

    .el-button {
      width: 100px;
      height: 40px;
      margin-right: 32px;
      background: #2265ee;
      border-box: 1px solid #2265ee;

      &:active {
        opacity: 0.8;
      }
    }
  }

  .sjform-tip {
    width: 100%;
    height: 46px;
    background: #fffbe8;
    border-radius: 4px;
    line-height: 46px;
    color: #ed6a0c;
    box-sizing: border-box;
    padding-left: 16px;
    margin-bottom: 16px;
    font-size: 14px;
    i {
      margin-right: 8px;
    }
  }
}

.edit-study {
  margin-top: 32px;

  ul {
    list-style: none;
    font-size: 19px;
    color: #0d162a;

    li {
      width: 176px;
      height: 53px;
      display: inline-block;
      line-height: 53px;
      text-align: center;
      cursor: pointer;
    }
  }
}

.active-study {
  background-color: #f6f8fc;
  border-radius: 5px 133px 0px 0px;
}

::v-deep .el-icon-my-zs {
  background: url("../../assets/images/zs1.png") no-repeat;
  width: 20px;
  height: 20px;
}

::v-deep .el-icon-my-zs:before {
  content: "替";
  font-size: 20px;
  visibility: hidden;
}

::v-deep .el-icon-my-zs {
  font-size: 18px;
}

::v-deep .el-icon-my-zs:before {
  content: "\e611";
}

.set-form-wid {
  width: 300px !important;
}

::v-deep .el-textarea__inner {
  resize: vertical !important;
}

.edit-footer-btn {
  background: none !important;
}

.set-btn-add {
  position: absolute;
  right: 40px;
  z-index: 1000;
}

.table-operations {
  margin-bottom: 16px;
  text-align: right;
}

::v-deep .el-table {
  .el-table__row {
    height: 48px;
  }

  .cell {
    display: flex;
    align-items: center;
    height: 100%;
    line-height: normal;
  }

  .el-table__body {
    width: 100% !important;
  }

  .el-table__header {
    width: 100% !important;
  }

  .el-table__body-wrapper {
    overflow-y: auto;
  }

  .gizall {
    width: 100%;
    display: flex;
    align-items: center;
    min-height: 23px;
  }
}

.delete-btn {
  color: #F56C6C;
  padding: 0;
  height: 23px;
  line-height: 23px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin: 0;

  .el-icon-delete {
    margin-right: 4px;
    font-size: 14px;
  }
}

.question-count-form {
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .el-form-item {
    margin-bottom: 8px;
    margin-right: 16px;
  }

  .question-count-limit {
    margin-left: 8px;
    color: #909399;
    font-size: 12px;
  }
}
</style>
